# -*- coding: utf-8 -*-
# Create your views here.
from django.views.generic.base import View
from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_page
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required



# def UserIs(user,ProjectUser):
#     try:
#         q = getattr(user,ProjectUser)
#         return True
#     except:
#         return False

class UserIs():

    ##
    #         用法
    #   @ClassViewDecorator(user_passes_test(UserIs("WikiUser").Test))
    def __init__(self,ProjectUser):
        self.ProjectUser = ProjectUser
    def Test(self,user):
        try:
            q = getattr(user,self.ProjectUser)
            return True
        except:
            return False



class BaseView(View):
    ## 修改了系统自带的View，加入一个setup（）的初始化函数
    def setup(self,request):
        self.response_dict = {}
        self.request = request

    def dispatch(self, request, *args, **kwargs):
        self.setup(request)
        return View.dispatch(self,request,*args,**kwargs)




    def template(self,template_file):
        self.template_file = template_file
        return self.template_file

    def ingroup(self,groupfullname):
        ## 判断当前用户时候在组
        return self.request.user.groups.filter(name=groupfullname).exists()

    def responsejson(self,data):
        from .DjangoJSONEncoder import dumps
        return HttpResponse(dumps(data), mimetype="application/json")

    def response(self,mimetype="text/html",template_file=None):

        if template_file == None:
            template_file == self.template_file
        else:
            pass

        return render_to_response(template_file,
            self.response_dict,
            mimetype=mimetype,
            context_instance=RequestContext(self.request,processors=[])
        )

    def go(self,urlname,args):

        ## 用法 return self.go(urlname="wiki-view-page",args=(page_id,))
        return HttpResponseRedirect(reverse(urlname, args=args))

    def nullgood(self):
        # 服务器成功处理了请求，但未返回任何内容。
        return HttpResponse(status=204)









def ClassViewDecorator(function_decorator):
    ###
    # 适用于类的权限判定
    # 使用方法：
    # @ClassViewDecorator(login_required)
    # class MyView(View):
    ###

    def simple_decorator(View):
        View.dispatch = method_decorator(function_decorator)(View.dispatch)
        return View

    return simple_decorator



def CachePage(cls=None, **cache_kwargs):
    """
    Apply the ``cache_page`` decorator to all the handlers in a class-based
    view that delegate to the ``dispatch`` method.

    Optional arguments
    ``timeout`` -- Cache timeout, in seconds.``

    Usage (without timeout parameter):
      @CachePage
      class MyView (TemplateView):
        ...

    Usage (with 5 minute timeout):
      @CachePage(60*5)
      class MyView(TemplateView):
        ...

    Based on login required decorator: http://djangosnippets.org/snippets/2495/
    """

    if cls is not None:
        # Check that the View class is a class-based view. This can either be
        # done by checking inheritance from django.views.generic.View, or by
        # checking that the ViewClass has a ``dispatch`` method.
        if not hasattr(cls, 'dispatch'):
            raise TypeError(('View class is not valid: %r.  Class-based views '
                             'must have a dispatch method.') % cls)

        timeout = None
        if cache_kwargs.has_key('timeout'):
            timeout = cache_kwargs.pop('timeout')
        original = cls.dispatch
        if timeout:
            modified = method_decorator(cache_page(timeout, **cache_kwargs))(original)
        else:
            modified = method_decorator(cache_page(**cache_kwargs))(original)
        cls.dispatch = modified

        return cls

    else:
        # If ViewClass is None, then this was applied as a decorator with
        # parameters. An inner decorator will be used to capture the ViewClass,
        # and return the actual decorator method.
        def inner_decorator(inner_cls):
            return CachePage(inner_cls, **cache_kwargs)

        return inner_decorator


class AjaxView(BaseView):
    pass